# -*- coding: utf-8 -*-
import json
import uuid

from conf.neo4j_cnx import NeoCnxPool

neo_cnx = NeoCnxPool()


class IcdKgCreator:

    @staticmethod
    def add_node(uid, child, parent, properties):
        with neo_cnx.get_session() as session:
            query = (
                'MERGE (a:ICD11 {uid: $uid}) '
                'ON CREATE SET '
                'a.child = $child, '
                'a.parent = $parent, '
                'a.properties = $properties'
            )
            properties = json.dumps(properties, ensure_ascii=False)
            session.run(query, uid=uid,
                        child=child, parent=parent,
                        properties=properties)

    @staticmethod
    def find_child_uids(uid):
        with neo_cnx.get_session() as session:
            query = (
                'MATCH (a:ICD11 {uid: $uid}) '
                'RETURN a.child as child '
            )
            results = session.run(query, uid=uid)
            results = [record['child'] for record in results.data()][0]
            return results

    def add_child(self, uid):
        with neo_cnx.get_session() as session:
            uid_list = self.find_child_uids(uid)
            query = (
                'MATCH (a:ICD11) '
                'MATCH (b:ICD11 {uid: $uid}) '
                'WHERE a.uid = $ch_uid '
                'MERGE (a)<-[r:Child]-(b) '
                'ON CREATE SET r.uid = $r_uid'
            )
            for ch_uid in uid_list:
                session.run(query, uid=uid, ch_uid=ch_uid, r_uid=str(uuid.uuid4()))

    @staticmethod
    def add_parent(uid):
        """
        One node only have one parent in the released ICD11 KG
        """
        with neo_cnx.get_session() as session:
            query = (
                'MATCH (a:ICD11) '
                'MATCH (b:ICD11 {uid: $uid}) '
                'WHERE a.uid in b.parent '
                'MERGE (b)-[r:Parent]->(a) '
                'ON CREATE SET r.uid = $r_uid'
            )
            session.run(query, uid=uid, r_uid=str(uuid.uuid4()))
